# 调用蓝图对象
from flask import render_template,current_app, jsonify
from flask import request
from flask import session

from info import constants
from info.models import User, News, Category
from info.utils.response_code import RET
from . import index1


"""
右上角实现:
1.在登陆的时候会返回一个session信息.
2.得到session信息里的ID,使用ID从redis里取出信息对象,
将信息对象里的局部信息返回存到data里,将其返回给前端.

3.前端获取到这信息后会返回图像,昵称等信息给浏览器.


"""



@index1.route('/')
def index():


    # 定义列表保存分类数据
    # 拼接内容

    user_id = session.get('user_id',None)
    user = None
    if user_id:
        try:
            user = User.query.get(user_id)

        except Exception as e:
            current_app.logger.error(e)


    #从数据库查出数据,把数据进行处理返回给前端.
    new_list = []
    try:
        new_list = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.error(e)

    new_dict_li = []
    for news in new_list:
        # print(news)
        new_dict_li.append(news.to_basic_dict())
        # print(news.to_basic_dict())
        # 获取新闻分类数据
        categories = Category.query.all()

        categories_dicts = []
        for i in categories:
            categories_dicts.append(i.to_dict())

    data = {
        # to_dict()是User下用户写的把我们想要的东西封装成字典的函数.
        # 如果user存在则执行前面的转换,如果不存在则为None.
        'news_dict_li': new_dict_li,
        'user': user.to_dict() if user else None,
        'category_li':categories_dicts
    }

    # 这里要先添加到模板文件才能有提示吧
    return render_template('news/index.html', data=data)


@index1.route('/favicon.ico')
def favicon_ico():
    # 发送静态文件
    # current_app可以简单理解为app的替身, 能够直接运行app相关的函数
    # send_static_file: 专门用于发送静态文件(图像/文本/js...)
    # current_app是在一个请求中, 自动产生的, 是app的代理对象
    return current_app.send_static_file('news/favicon.ico')
# current_app.send_static_file('news/favicon.ico')

@index1.route('/news_list')
def get_news_list():
    # 获取前端发送来的数据
    args_dict = request.args
    # 取出p对应的值,默认为一
    page = args_dict.get('page', '1')
    # page:分类ID,per_page:页码,
    per_page = args_dict.get('per_page', constants.HOME_PAGE_MAX_NEWS)
    cid = args_dict.get('cid', '1')

    try:
        page = int(page)
        cid = int(cid)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg='参数传入错误')

    filter = []

    if cid !=1:
        filter.append(News.category_id ==cid)

    try:
        paginate = News.query.filter(*filter).order_by(News.create_time.desc()).paginate(page, per_page, False)

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg='查询失败')
    # 固定的语法
    # 获得查询后的数据
    news_model_list = paginate.items

#     获得分页的总页码
    total_page = paginate.pages
    # 获得当前页码
    current_page = paginate.page

    new_dict_li = []

    for news in news_model_list:

        new_dict_li.append(news.to_basic_dict())

    data = {
        'news_dict_li':new_dict_li,
        'total_page':total_page,
        'current_app':current_page
    }

    return jsonify(errno=RET.OK,errmsg='成功', data=data)
